import React from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Upload,
  Modal,
  message,
  Icon,
  Switch,
  Select
} from 'antd';
import {connect} from 'dva';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {FormComponentProps} from 'antd/es/form';
import {ModelState} from './model';
import {Dispatch} from 'redux';
import {UploadChangeParam} from 'antd/lib/upload';
import {UploadFile} from 'antd/lib/upload/interface';
import router from "umi/router";
import styles from './style.less'

const FormItem = Form.Item;
const {Option} = Select;

interface IProps extends FormComponentProps {
  adminSave: ModelState;
  loading: boolean;
  dispatch: Dispatch<any>;
  location: any;
  match: any;
}

interface IStates {
  selectedRowKeys: any[];
  formValues: object;
  previewImageUrl: string;
  preViewModalVisible: boolean;
}

const formItemLayout = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 8},
    md: {span: 3},
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 12},
    md: {span: 18},
  },
};
const submitFormLayout = {
  wrapperCol: {
    xs: {span: 24, offset: 0},
    sm: {span: 10, offset: 3},
  },
};

class Index extends React.Component<IProps, IStates> {
  state: IStates = {
    selectedRowKeys: [],
    formValues: {},
    previewImageUrl: '',
    preViewModalVisible: false,
  };

  componentDidMount() {
    const {dispatch, match} = this.props;
    const id = match.params.id;

    dispatch({
      type: 'adminSave/fetchDetail',
      payload: {id}
    });

  }


  UploadButton = (
    <div>
      <Icon type="plus"/>
      {/*<Icon type={this.state.loading ? 'loading' : 'plus'}/>*/}
      {/*<div className="ant-upload-text">头像上传</div>*/}
    </div>
  );

  //UploadChangeParam
  handleUploadChange = (info: UploadChangeParam): any => {
    let fileList = info.fileList;
    if (info.file.status === 'done') {
      message.success(`${info.file.name}文件上传成功`);
    }
    return fileList.slice(-1);
  };

  //UploadFile
  photoPreview = (file: UploadFile) => {
    const fileUrl = file.url || file.thumbUrl;
    this.setState({
      previewImageUrl: fileUrl as string,
      preViewModalVisible: true,
    });
  };

  previewModalCancel = () => {
    this.setState({
      preViewModalVisible: false,
    });
  };


  handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const {form, dispatch, match} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (!err) {
        fieldsValue.avatar = fieldsValue.avatar.map((item: any) => ({
          uid: item.uid,
          name: item.name,
          url: item.url ? item.url : item.response.data.file_url
        }));
        dispatch({
          type: 'adminSave/addAndUpdate',
          payload: {id: match.params.id, ...fieldsValue}
        });
      }
    });
  };

  render() {
    const {form, adminSave: {detail, roles}, loading, match} = this.props;
    const getFieldDecorator = form.getFieldDecorator;


    const routes = [
      {
        path: 'index',
        breadcrumbName: '主页',
      },
      {
        path: 'account',
        breadcrumbName: '账号管理',
      },
      {
        path: 'admin',
        breadcrumbName: '用户管理',
      },
      {
        path: 'add',
        breadcrumbName: '添加用户',
      },
    ];
    if (match.params.id > 0) {
      routes[routes.length - 1] = {
        path: 'save',
        breadcrumbName: '修改用户',
      };
    }


    return (
      //@ts-ignore
      <PageHeaderWrapper title={false} breadcrumb={{routes}}>
        <Card bordered={false}>
          <Form layout="horizontal" {...formItemLayout} onSubmit={this.handleSubmit}>

            <FormItem label="头像">
              {getFieldDecorator('avatar', {
                rules: [
                  {
                    required: true,
                    message: '请先上传头像',
                  },
                ],
                getValueFromEvent: this.handleUploadChange,
                valuePropName: 'fileList',
                initialValue: detail.avatar || [],
              })(
                <Upload
                  listType="picture-card"
                  accept=".jpg,.jpeg,.png"
                  action="http://106.13.168.150:9501/upload/photo"
                  name="photo"
                  showUploadList={{showPreviewIcon: true, showRemoveIcon: true}}
                  // onChange={this.handleUploadChange}
                  onPreview={this.photoPreview}
                  // fileList={this.state.fileList}
                  className={styles.uploadListInline}
                >
                  {/*{this.props.form.getFieldValue('thumb').length > 1 ? null : this.UploadButton}*/}
                  {this.UploadButton}
                </Upload>,
              )}
              <Modal
                visible={this.state.preViewModalVisible}
                footer={null}
                onCancel={this.previewModalCancel}
              >
                <img alt="example" style={{width: '100%'}} src={this.state.previewImageUrl}/>
              </Modal>
            </FormItem>

            <FormItem label="昵称">
              {getFieldDecorator('nickname', {
                rules: [
                  {
                    required: true,
                    message: '昵称不能为空',
                  },
                ],
                initialValue: detail.nickname || ''
              })(<Input placeholder={'请输入昵称'} style={{width: 250}}/>)}
            </FormItem>

            <FormItem label="用户">
              {getFieldDecorator('username', {
                rules: [
                  {
                    required: true,
                    message: '用户名不能为空',
                  },
                ],
                initialValue: detail.username || ''
              })(<Input placeholder={'请输入用户名'} style={{width: 250}}/>)}
            </FormItem>
            <FormItem label="密码">
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: '密码不能为空',
                  },
                ],
                initialValue: detail.password || ''
              })(<Input placeholder={'请输入密码'} style={{width: 400}}/>)}
            </FormItem>

            <FormItem label="邮箱">
              {getFieldDecorator('email', {
                initialValue: detail.email || ''
              })(<Input placeholder={'请输入邮箱'} type="email" style={{width: 400}}/>)}
            </FormItem>

            <FormItem label="角色">
              {getFieldDecorator('role_ids', {
                rules: [
                  {
                    required: true,
                    message: '请选择角色',
                  },
                ],
                valuePropName: 'value',
                initialValue: detail.role_ids || []
              })(
                <Select
                  mode="multiple"
                  style={{width: 400}}
                  placeholder="请选择角色"
                >
                  {roles.map((item) => <Option key={item.id} value={item.id}>{item.title}</Option>)}
                </Select>
              )}
            </FormItem>

            <FormItem label="状态">
              {getFieldDecorator('status', {
                rules: [
                  {
                    required: true,
                  },
                ],
                valuePropName: 'checked',
                initialValue: true
              })(<Switch checkedChildren="启用" unCheckedChildren="禁用"/>)}
            </FormItem>

            <FormItem {...submitFormLayout}>
              <Button type="primary" htmlType="submit" loading={loading}>
                提交
              </Button>
              <Button style={{marginLeft: 8}} onClick={() => {
                router.goBack();
              }}>返回</Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<IProps>()(
  connect(
    ({
       adminSave,
       loading,
     }: {
      adminSave: ModelState;
      loading: {
        effects: { [key: string]: boolean }
      };
    }) => ({
      adminSave,
      loading: loading.effects['adminSave/addAndUpdate'],
    }),
  )(Index),
);
